import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {Component} from 'react'
import Modal from 'react-native-modalbox';
import {border, default as styles, HUNDRED_PERCENT, margin, padding} from "../../../../style";
import {AppIcon} from "../../../../assets/icon/AppIcon";
import Stepper from "../../../widget/Stepper";
import {Actions} from "react-native-router-flux";
import {BuyFlag} from "../../../widget/ShopToolBar";
import {inject, observer} from "mobx-react/custom";
import {Store} from "../../../../store";
import {ProductStore} from "../../../../store/modules/main/product";
import {afterAnimation, defaultArr, defaultObj, getAssetUrl} from "../../../../util";
import FastImageCustom from "../../../widget/FastImageCustom";
import {ProductSpecificationInterface} from "../../../../net/instance/CommenModelInstance";
import {CertStore} from "../../../../store/modules/cert";
import toast from "../../../common/ToastProxy";

interface DetailModalProps extends Store {

}

interface DetailModalState {
    flag: BuyFlag,
    selectedSpecification?: ProductSpecificationInterface
}

@inject("product", "cert")
@observer
export default class DetailModal extends Component<DetailModalProps, DetailModalState> {

    product: ProductStore;
    cert: CertStore;
    stepper: Stepper;
    state: DetailModalState = {
        flag: BuyFlag.Buy,
        selectedSpecification: defaultObj,
    };

    constructor(props: DetailModalProps) {
        super(props);
        this.product = this.props.product;
        this.cert = this.props.cert;
    }

    /***
     * 获取商品规格信息
     * @param {number} productId
     * @returns {Promise<void>}
     */
    async refresh(productId: number) {
        await this.product.getProductSpecificationById(productId);
        await this.product.getUserProductLimit(productId);
        const {productSpecifications = defaultArr} = this.product;
        //默认选择第0个
        if (productSpecifications.length) {
            this.setState({
                selectedSpecification: productSpecifications[0]
            })
        }
    }


    get buyBtnLabel() {
        const label = this.state.flag === BuyFlag.Buy ? "购买" : "加入购物车";
        return this.product.cantBuyAnyMore ? "数量已上限" : label;
    }

    showModal(flag: BuyFlag) {
        this.setState({
            flag
        });
        this.modal.open();
    }

    hideModal = () => {
        this.modal.close();
    };

    /***
     * 买单
     */
    checkBill = () => {
        if (this.product.cantBuyAnyMore) return;
        const orderItem = {
            product: this.product.productDetail,
            count: this.stepper.getCount(),
            maxCount:this.product.buyMaxCount,
            selectedSpecification: this.state.selectedSpecification || null
        };
        if (this.state.flag === BuyFlag.Buy) {
            Actions.push("CheckBill", {
                orderList: [orderItem]
            });
        } else {
            this.cert.addOrderItem(orderItem);
            afterAnimation(async () => {
                global.showSuccess("添加成功！")
            });
        }
    };

    chooseSpecification = (spec: ProductSpecificationInterface) => {
        return () => {
            this.setState({
                selectedSpecification: spec
            })
        }
    };
    modal: Modal;

    get productPrice() {
        const {productSpecifications, productDetail} = this.props.product;
        return productSpecifications.length ? this.state.selectedSpecification.price : productDetail.price;
    }

    render() {
        const {name, imageUrl, price, infoImageUrl} = this.product.productDetail;
        const {productSpecifications = defaultArr} = this.product;
        return (<Modal backdropPressToClose={true}
                       swipeToClose={false}
                       backdrop={true}
                       position={"bottom"}
                       style={[{backgroundColor: "#fff", width: HUNDRED_PERCENT, height: null}]}
                       ref={modal => this.modal = modal}>
            <View style={padding(12, 0)}>
                <View style={[styles.flexDirectionRowNotFlex, padding(0, 12)]}>
                    <FastImageCustom source={{uri: getAssetUrl(infoImageUrl)}} style={{width: 100, height: 100}}
                                     resizeMode={"contain"}/>
                    <View style={[styles.flex, margin(10), styles.justifyBetween]}>
                        <Text style={{color: "#333333", fontSize: 16}}>{name}</Text>
                        <Text style={{color: "#333333", fontSize: 16, fontWeight: "bold"}}>￥{this.productPrice}</Text>
                    </View>
                    <TouchableOpacity onPress={this.hideModal}>
                        <AppIcon name={"guanbi"} color={"#000000"} size={15}/>
                    </TouchableOpacity>
                </View>
                {productSpecifications.length ?
                    <View style={[padding(6, 12), {marginTop: 17, borderBottomWidth: 0.5, borderColor: "#ccc"}]}>
                        <Text style={{fontSize: 14, color: "#333333"}}>规格</Text>
                        <View style={[styles.flexDirectionRowNotFlex, margin(10, 0)]}>
                            {productSpecifications.map((spec) => {
                                const {name, id} = spec;
                                const activeColor = spec.id === this.state.selectedSpecification.id ? "#15823B" : "#ccc";
                                return <TouchableOpacity onPress={this.chooseSpecification(spec)} activeOpacity={.7}
                                                         key={id}
                                                         style={[padding(4, 14), border(1, activeColor), {
                                                             borderRadius: 30,
                                                             marginRight: 20
                                                         }]}>
                                    <Text style={{fontSize: 14, color: activeColor}}>{name}</Text>
                                </TouchableOpacity>
                            })}
                        </View>
                    </View> : null}
                <View style={[styles.flexDirectionRowNotFlex, styles.centerH, padding(0, 12), {marginTop: 17}]}>
                    <Text style={{fontSize: 14, color: "#333333"}}>数量</Text>
                    <Stepper maxCount={this.product.buyMaxCount} ref={stepper => this.stepper = stepper} count={1}
                             style={[margin(0, 18, 0, 33)]}
                             countContainerStyle={{width: 82}}/>
                </View>
                <View style={[padding(15), {paddingBottom: 0}]}>
                    <TouchableOpacity
                        activeOpacity={.7}
                        style={[styles.centered, {
                            borderRadius: 30,
                            height: 40,
                            backgroundColor: this.product.cantBuyAnyMore ? "#ccc" : "#629C36"
                        }]}
                        onPress={this.checkBill}>
                        <Text style={{fontSize: 14, color: "#fff"}}>{this.buyBtnLabel}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </Modal>)
    }
}

const style = StyleSheet.create({
    container: {}
});

 